Visualization | Social Network Analysis¶

Dr. Chan, Chun-Hsiang @ Department of Geography,
National Taiwan Normal University, Taipei, Taiwan

In [1]:
# import packages
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from pyvis import network as net

Create a Random Graph¶

In [2]:
# create Erdos Renyi random graph
G = nx.erdos_renyi_graph(50, 0.5, seed=21, directed=False)
In [3]:
# set options
options = {
    "font_size": 8,
    "node_size": 100,
    "node_color": "#A0CBE2",
    "edge_color": "brown",
    "linewidths": 0.1,
    "width": 0.08,
}
In [4]:
# circular
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_circular(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()
In [5]:
# kamada kawai
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_kamada_kawai(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()
In [6]:
# shell
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_shell(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()
In [7]:
# spectral
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_spectral(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()
In [8]:
# spring
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_spring(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()
In [9]:
plt.subplots(figsize=[12,6], dpi=100)
nx.draw_random(G,  **options, with_labels = True)
ax = plt.gca()
ax.margins(0.001)
plt.axis("off")
plt.show()

Pyvis¶

In [10]:
# create vis network 
visG = net.Network(notebook=True, height="800px", width="100%", bgcolor="#222222",
                   font_color="white", filter_menu=True, select_menu=True, cdn_resources='remote')
# import graph from networkx
visG.from_nx(G)
# show
visG.show_buttons() #filter_=['physics']
visG.show('pyvis_ex.html')
pyvis_ex.html
Out[10]:
In [11]:
# extract networkx node to dataframe
G_nodes = pd.DataFrame.from_records(np.row_stack(list(G.nodes)), columns=['ID'])
# add size with random values
G_nodes['size'] = abs(np.random.normal(15, 12, G_nodes.shape[0]))
# add group with random values
G_nodes['group'] = np.random.randint(15, size=G_nodes.shape[0])+1
# add node label with random values
G_nodes['code'] = 'S_'+G_nodes['ID'].astype('str')
# preview data
G_nodes.head()
Out[11]:
ID size group code
0 0 18.904882 12 S_0
1 1 4.296053 12 S_1
2 2 16.318094 7 S_2
3 3 17.204384 10 S_3
4 4 31.239146 13 S_4
In [12]:
# extract networkx edge to dataframe
G_edges = pd.DataFrame.from_records(np.row_stack(list(G.edges)), columns=['source','target'])
# add weight with random values
G_edges['weight'] = np.sqrt(abs(np.random.normal(100, 25, G_edges.shape[0])))
# preview data
G_edges.head()
Out[12]:
source target weight
0 0 1 11.184265
1 0 4 11.314539
2 0 5 7.641624
3 0 10 10.133994
4 0 11 9.898726
In [13]:
color_map = {1:'#CCFF00', 2:'#CCCC33', 3:'#CC9966', 4:'#CC6699', 5:'#CC33CC', 6:'#CC00FF',  
                 7:'#9900FF', 8:'#6600CC', 9:'#660066', 10:'#660033', 11:'#CC99FF', 12:'#FFCCFF', 
                 13:'#FFFFCC', 14:'#FF3300', 15:'#333333', 16:'#666666'} 
options = {
        'edge_color': '#FFDEA2',
        'width': .5,
        'with_labels': False,
        'font_weight': 'regular',
    }
In [14]:
# initialize 
g = net.Network(height="800px", width="100%", bgcolor="#222222", font_color="white",  
                filter_menu=True, select_menu=True, cdn_resources='remote')
# add node
for i in range(len(G_nodes['code'])): 
    g.add_node(int(G_nodes['ID'][i]), size=int(G_nodes['size'][i]), label=G_nodes['code'][i],
               group=int(G_nodes['group'][i]))
# add edge
for i in range(len(G_edges)):
    g.add_edge(int(G_edges['source'][i]), int(G_edges['target'][i]), weight=G_edges['weight'][i])
# add options
g.set_template_dir = None
g.show_buttons()
# export
g.show('adv_ex.html', notebook=False)
adv_ex.html

Export¶

In [15]:
G_nodes.to_csv('ex_node.csv', index=False)
G_edges.to_csv('ex_edge.csv', index=False)